extends InteractiveObject3D

enum State {OPEN, CLOSED}
enum OpenDirection {CW, CCW}

@onready var hinge: HingeJoint3D = $hinge
@onready var door_pivot = $door_pivot
@onready var door = $door_pivot/door

@export var state = State.CLOSED
@export var open_direction = OpenDirection.CW

var cutout_angle = INF

const openPositionDeg = {
	OpenDirection.CW: -90,
	OpenDirection.CCW: 90
}

# Opposite for closing
const motorTargetOpenVelocity = {
	OpenDirection.CW: -1,
	OpenDirection.CCW: 1
}

# Called when the node enters the scene tree for the first time.
func _ready():
	if state == State.OPEN:
		door_pivot.rotation.y = -deg_to_rad(openPositionDeg[open_direction])
		
	hinge.set_param(HingeJoint3D.Param.PARAM_LIMIT_LOWER, deg_to_rad(min(openPositionDeg[open_direction], 0)))
	hinge.set_param(HingeJoint3D.Param.PARAM_LIMIT_UPPER, deg_to_rad(max(openPositionDeg[open_direction], 0)))

func _process(delta):
	if hinge.get_flag(HingeJoint3D.FLAG_ENABLE_MOTOR):
		print(round(rad_to_deg(door.rotation.y)))
		if round(rad_to_deg(door.rotation.y)) == cutout_angle:
			pass
			#hinge.set_flag(HingeJoint3D.FLAG_ENABLE_MOTOR, false)
			#door.linear_velocity = Vector3.ZERO
			#door.angular_velocity = Vector3.ZERO

func interact(params: Dictionary = {}) -> void:
	state = State.OPEN if state == State.CLOSED else State.CLOSED
	var motorDirection = motorTargetOpenVelocity[open_direction]
	var cutout_angle = 90
	self.cutout_angle = cutout_angle
	if state == State.CLOSED:
		motorDirection *= -1
	print(motorDirection)
	hinge.set_param(HingeJoint3D.Param.PARAM_MOTOR_TARGET_VELOCITY, motorDirection)
	hinge.set_flag(HingeJoint3D.FLAG_ENABLE_MOTOR, true)
